using MedicalReportAssistant.Models;
using Newtonsoft.Json;
using System.Text;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using System.Net.Http;
using System;
using System.Threading.Tasks;

namespace MedicalReportAssistant.Services
{
    public class QwenCorrectionService : ICorrectionService
    {
        private readonly HttpClient _httpClient;
        private readonly ILogger<QwenCorrectionService> _logger;
        private readonly IConfiguration _configuration;
        private readonly string _apiUrl;
        private readonly string _model;
        private readonly int _maxTokens;
        private readonly double _temperature;
        private readonly string _apiKey;

        public QwenCorrectionService(HttpClient httpClient, ILogger<QwenCorrectionService> logger, IConfiguration configuration)
        {
            _httpClient = httpClient;
            _logger = logger;
            _configuration = configuration;
            _apiUrl = _configuration["Qwen:ApiUrl"] ?? "http://localhost:8000/v1/chat/completions";
            _model = _configuration["Qwen:Model"] ?? "Qwen-7B-Chat";
            _maxTokens = _configuration.GetValue<int>("Qwen:MaxTokens", 2000);
            _temperature = _configuration.GetValue<double>("Qwen:Temperature", 0.1);
            _apiKey = _configuration["Qwen:ApiKey"] ?? string.Empty;
            if (!string.IsNullOrEmpty(_apiKey))
            {
                _httpClient.DefaultRequestHeaders.Remove("Authorization");
                _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
            }
            _httpClient.Timeout = TimeSpan.FromSeconds(30);
        }

        public async Task<CorrectionResult> CorrectMedicalReportAsync(string originalText)
        {
            ArgumentException.ThrowIfNullOrWhiteSpace(originalText);
            try
            {
                var prompt = BuildCorrectionPrompt(originalText);
                var request = new
                {
                    model = _model,
                    messages = new[]
                    {
                        new { role = "system", content = GetSystemPrompt() },
                        new { role = "user", content = prompt }
                    },
                    temperature = _temperature,
                    max_tokens = _maxTokens
                };
                var json = JsonConvert.SerializeObject(request);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                _logger.LogInformation("正在发送请求到本地Qwen API...");
                _logger.LogInformation($"请求内容: {json}");
                using var response = await _httpClient.PostAsync(_apiUrl, content);
                var responseContent = await response.Content.ReadAsStringAsync();
                _logger.LogInformation($"API响应内容: {responseContent}");
                if (!response.IsSuccessStatusCode)
                {
                    return new CorrectionResult
                    {
                        Success = false,
                        ErrorMessage = $"Qwen API请求失败: {response.StatusCode}\n{responseContent}",
                        OriginalText = originalText,
                        CorrectedText = originalText
                    };
                }
                var responseObj = JsonConvert.DeserializeObject<DeepSeekResponse>(responseContent);
                if (responseObj?.Choices?.FirstOrDefault()?.Message?.Content != null)
                {
                    return ParseCorrectionResult(responseObj.Choices[0].Message.Content!, originalText);
                }
                return new CorrectionResult
                {
                    Success = false,
                    ErrorMessage = "Qwen API返回空响应",
                    OriginalText = originalText,
                    CorrectedText = originalText
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "调用Qwen API失败");
                return new CorrectionResult
                {
                    Success = false,
                    ErrorMessage = $"Qwen API调用失败: {ex.Message}",
                    OriginalText = originalText,
                    CorrectedText = originalText
                };
            }
        }

        private static string GetSystemPrompt()
        {
            return DeepSeekService.GetSystemPrompt();
        }
        private static string BuildCorrectionPrompt(string originalText)
        {
            return DeepSeekService.BuildCorrectionPrompt(originalText);
        }
        private CorrectionResult ParseCorrectionResult(string response, string originalText)
        {
            return (new DeepSeekService(null!, null!, null!)).ParseCorrectionResult(response, originalText);
        }
    }
} 